package com.gqzmy.springboot3.exceptions;

import io.micrometer.common.util.StringUtils;

import java.io.Serial;

/**
 * @author 周小哥  gqzmy@163.com 2022/12/1 12:30
 */

public class SystemException extends Exception {
    @Serial
    private static final long serialVersionUID = 2100321464193348511L;

    private int errCode;

    private String errMsg;

    private Throwable causeThrowable;

    public SystemException() {
    }

    public SystemException(final int errCode, final String errMsg) {
        super(errMsg);
        this.errCode = errCode;
        this.errMsg = errMsg;
    }

    public SystemException(final int errCode, final Throwable throwable) {
        super(throwable);
        this.errCode = errCode;
        this.setCauseThrowable(throwable);
    }

    public SystemException(final int errCode, final String errMsg, final Throwable throwable) {
        super(errMsg, throwable);
        this.errCode = errCode;
        this.errMsg = errMsg;
        this.setCauseThrowable(throwable);
    }

    public int getErrCode() {
        return this.errCode;
    }

    public String getErrMsg() {
        if (!StringUtils.isBlank(this.errMsg)) {
            return this.errMsg;
        }
        if (this.causeThrowable != null) {
            return this.causeThrowable.getMessage();
        }
        return "";
    }

    public void setErrCode(final int errCode) {
        this.errCode = errCode;
    }

    public void setErrMsg(final String errMsg) {
        this.errMsg = errMsg;
    }

    public void setCauseThrowable(final Throwable throwable) {
        this.causeThrowable = this.getCauseThrowable(throwable);
    }

    private Throwable getCauseThrowable(final Throwable t) {
        if (t.getCause() == null) {
            return t;
        }
        return this.getCauseThrowable(t.getCause());
    }

    @Override
    public String toString() {
        return "SystemException{" +
                "errCode=" + errCode +
                ", errMsg='" + errMsg + '\'' +
                ", causeThrowable=" + causeThrowable +
                '}';
    }
}
